package com.mrd.util;

import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.entity.Booking;
import com.mrd.gtimp.business.entity.Goods;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 主键清除工具类
 *
 * @author luob
 */
public class PkCleanerUtil {
    /**
     * 主键清除工具方法
     *
     * @param pkConfig 详细配置参考对象文档
     */
    public static void clearPk(Object entity, PkConfig[] pkConfig) throws SecurityException,
            NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
            InvocationTargetException {
        if (entity == null) {
            return;
        }
        for (PkConfig pkc : pkConfig) {
            String mName = "set";
            Class<?>[] parameterTypes = new Class<?>[]{pkc.getParameterType()};
            if (pkc.getPk().indexOf("|O") != -1) {//string
                mName += pkc.getPk().substring(0, 1).toUpperCase()
                        + pkc.getPk().substring(1, pkc.getPk().indexOf("|O"));
            } else {
                mName += pkc.getPk().substring(0, 1).toUpperCase() + pkc.getPk().substring(1);

            }
            Method m = entity.getClass().getMethod(mName, parameterTypes);
            if (pkc.getPk().indexOf("|O") == -1) {//string
                m.invoke(entity, "");
            } else {
                m.invoke(entity, new Object[]{null});
            }
        }
    }

    public static void main(String[] args) {
        Booking entity = new Booking();
        entity.setId("1024");
        entity.setCtime(new Date());
        entity.setUploader(new User());
        entity.setGoodses(new ArrayList<Goods>());
        PkConfig[] pkConfig = {new PkConfig("id", String.class),
                new PkConfig("CTIME|O", Date.class), new PkConfig("uploader|O", User.class),
                new PkConfig("goodses|O", List.class)};
        System.out.println(entity.getId() + "\t" + entity.getCtime() + "\t" + entity.getUploader()
                + "\t" + entity.getGoodses());
        try {
            clearPk(entity, pkConfig);
            System.out.println(entity.getId() + "\t" + entity.getCtime() + "\t"
                    + entity.getUploader() + "\t" + entity.getGoodses());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
